<template>
  <view :class="bgGray ? 'big-gray' : ''">
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <view class="cut-down" v-if="cmsClickparam=='task' && doTask!==3">
      <cutDown :requiredTime='requiredTime' :doTask='doTask'></cutDown>
    </view>
    <view class="cmsPage" :class="bgGray ? 'bg-gray' : ''">
      <view class="space" style="height: 74rpx;" v-if="cmsClickparam=='task' && doTask!==3"></view>
      <wxParse v-if="identifier" ref="cmsPage" @pageTitle="pageTitle" :isCurrentPage="isCurrentPage"
        :preview.sync="preview" :identifier.sync="identifier" :isAppend.sync="isAppend" :isIpx.sync="isIpx"
        :bgGray.sync="bgGray"></wxParse>
      <register-widget ref="registerWidgetRef" location="cms" :entrance="entrance" />
    </view>
  </view>
</template>
<script>
  import api from '@/api/api';
  import tip from '@/utils/tip';
  import NavBar from '../../components/common/navbar';
  import WxParse from '../../components/wxparse/wxparse';
  import registerWidget from "@/components/register/register-widget.vue"
  import cutDown from './cutdown.vue';
  import cmsMethods from '@/utils/cmsItems.js';
  import {
    SEL_CLASS_CODE,
    SEL_ACTIVE_CODE,
    SYSTEM_INFO,
    CUSTOMER_INFO,
    CART_KEY,
    MERCHANT_INFO,
    MEMBER_INFO
  } from '@/utils/constant';

  export default {
    config: {
      navigationBarTitleText: '小程序商城',
      navigationStyle: 'custom'
    },
    components: {
      navBar: NavBar,
      wxParse: WxParse,
      registerWidget: registerWidget,
      cutDown: cutDown
    },
    data() {
      return {
        // 组件所需的参数
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: this.$store.state.storeName, //导航栏 中间的标题
          hideSearch: false, //隐藏搜索
          backPreviewPage: 0, //返回上级页面 只显示返回按钮
          isTopFixed: false,
        },
        isShowCustomNavBar: true,
        title: '',
        windowHeight: 0,
        backgroundImage: 'https://www.cosstores.cn/img/dm/pageup/190318/sale-mob.jpg',
        cmsConfigData: [],
        identifier: 'cms/page',
        preview: false,
        isAppend: '',
        isIpx: '',
        pathOption: '',
        merchantId: '',
        storeId: '',
        previewpage: '',
        isCurrentPage: '',
        cmsShareIdentifier: "forward",
        defaultShareImage: '',
        shareImage: '', // CMS动态转发图片
        isFullOld: false, //默认不显示18周岁授权弹层
        cmsClickparam: '',
        pathTrackEn: '',
        pathTrackEp: '',
        bgGray: false,
        doTask: '',
        taskContentId: '',
        taskContentName: '',
        taskCenterCode: '',
        requiredTime: 10,
        shareDefaultImage: '',
        shareDefaultTitle: '',
        entrance: false,
        shareTitle: ''
      };
    },


    onShow() {
      let that = this;
      uni.setStorageSync(SEL_CLASS_CODE, '');
      uni.setStorageSync(SEL_ACTIVE_CODE, -1);
      let pages = getCurrentPages();
      this.isCurrentPage = pages[pages.length - 1].route;
      let prevpage = pages[pages.length - 2];
      if (prevpage == undefined) {
        this.previewpage = '';
      } else {
        this.previewpage = prevpage.route ? prevpage.route : '';
      }
      this.$refs.cmsPage.updateUserLoginState()
    },

    async onLoad(option) {
      let nowTime = new Date().getTime();
      let identifier = decodeURIComponent(option.identifier) == "cms/shoppingInstructions" && this.$programSetting
        .openAppointment ? "cms/appointmentInstructions" : decodeURIComponent(option.identifier) ==
        "cms/shoppingInstructions" && !this.$programSetting.openAppointment ? "cms/shoppingInstructions" : option
        .identifier
      if (option.scene) {
        identifier = await this.getScence(option.scene)
      }
      let pages = getCurrentPages();
      if (pages.length === 1) {
        await this.$onLaunched;
      }
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      if (!merchantInfo) {
        tip.plainText('没有获取到商户信息')
      }
      this.pathOption = identifier;
      this.cmsClickparam = option.type;
      this.pathTrackEn = option.en;
      this.pathTrackEp = option.ep;
      this.activityName = !!option.activityName ? option.activityName : ''
      let commonApp = getApp();
      //ts落地页 小程序第一次访问记缓存
      if (!!option.isTopFixed) {
        this.navbarData.isTopFixed = option.isTopFixed
      }
      if (!!option.hideHome) {
        this.navbarData.hideHome = option.hideHome
      }
      if (!!option.backColor) {
        this.navbarData.backColor = option.backColor
      }
      if (option.type == 'task') {
        await this.taskStatus()
      }
      let that = this;

      if (!!this.pathTrackEp) {
        let params = this.pathTrackEp.indexOf("'") !== -1 ? JSON.parse(this.pathTrackEp.replace(/'/g, '"')) : JSON
          .parse(this.pathTrackEp)
        if (params.c_link_path == '/pages/cms/page') {
          params.c_link_path = params.c_link_path + '?identifier=' + identifier
        }
        getApp().commonClTrack(this.pathTrackEn, params);
        this.setShareInfo()
      }

      let systemInfo = uni.getStorageSync(SYSTEM_INFO);
      if (
        systemInfo.model.indexOf('iPhone X') !== -1 ||
        systemInfo.model.indexOf('iPhone 1') !== -1 ||
        systemInfo.model.indexOf('iPhone 5') !== -1 ||
        systemInfo.model.indexOf('iPhone 7') !== -1 ||
        systemInfo.model.indexOf('iPhone 8') !== -1
      ) {
        this.isIpx = true;
      }
      if (systemInfo.model.indexOf('iPhone XS Max') !== -1 || systemInfo.model.indexOf('iPhone XS') !== -1) {
        this.isIpx = false;
      }
      this.identifier = identifier ? identifier : this.identifier;

      this.preview = option.preview ? option.preview : false;
      this.isAppend = option.isAppend;
      this.title = option.title ? option.title : this.title;
      // let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      this.merchantId = merchantInfo.cloudMerchantId;
      this.storeId = merchantInfo.cloudMerchantStoreId;
      that.windowHeight = systemInfo.windowHeight;
      this.getCMSPageInfo(this.cmsShareIdentifier, this.merchantId, this.storeId);
      if (this.identifier == 'cms/protectionPolicy' || this.identifier == 'cms/privacy' || this.cmsClickparam ==  'sdk') {
        that.entrance = false;
      }

      // 神策埋点  内容详情页浏览模块名称
      let _trackData = {page_label: this.identifier};
      if(option && option.first_module_name) _trackData.first_module_name = option.first_module_name || "";
      if(option && option.second_module_name) _trackData.second_module_name = option.second_module_name || "";

      this.$commonSensors.contentPageView('ContentPageView', _trackData)
    },
    onShareAppMessage: async function(res) {
      if (res.from === 'button') {
        // 来自页面内转发按钮
      } else {
        this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
      }
      let that = this
      let path
      if (this.cmsClickparam == 'scantask') {
        path = '/pages/home/home'
      } else {
        path = '/pages/cms/page?identifier=' + this.pathOption
      }
      let shareImg = this.shareImage || this.defaultShareImage
      let shareTitle = uni.getStorageSync('storeName') || '小程序商城'
			this.$sr.setContext({ share_title: shareTitle });
      let identifier = this.identifier
      let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      let mt = '1.0';
      this.$commonSensors.sensorsPageShare()
      const json = await api.getConfigDetail({
        method: 'POST',
        query: {
          "identifier": identifier + '-share',
          "merchantId": this.merchantId,
          "storeId": this.storeId,
          "mt": mt
        }
      });
      if (json.data.code === 1000 && json.data.data !== null) {
        let configData = json.data.data;
        let cmsConfigData = {};
        cmsConfigData = JSON.parse(configData.preview);
        shareImg = cmsConfigData[0][0].data.src
        shareTitle = cmsConfigData[0][0].data.title
        return this.$commonFunction.commonShare(res, shareTitle, path, shareImg);
      } else {
        return this.$commonFunction.commonShare(res, shareTitle, path, shareImg);
      }
    },
    onShareTimeline() {
      let that = this
      return {
        title: that.shareTitle,
        query: 'identifier=' + this.pathOption,
        imageUrl: that.shareImage
      }
    },
    methods: {
      setShareInfo: async function() {
        let that = this
        let shareImg = this.shareImage || this.defaultShareImage
        let shareTitle = uni.getStorageSync('storeName') || '小程序商城'
        let identifier = this.identifier
        let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
        let mt = '1.0';
        const json = await api.getConfigDetail({
          method: 'POST',
          query: {
            "identifier": identifier + '-share',
            "merchantId": this.merchantId,
            "storeId": this.storeId,
            "mt": mt
          }
        });
        if (json.data.code === 1000 && json.data.data !== null) {
          let configData = json.data.data;
          let cmsConfigData = {};
          cmsConfigData = JSON.parse(configData.preview);
          this.shareImage = cmsConfigData[0][0].data.src
          this.shareTitle = cmsConfigData[0][0].data.title
        } else {
          this.shareTitle = uni.getStorageSync('storeName') || '小程序商城'
        }
      },
      // 获取自定义参数
      getScence: async function(key) {
        const sence = await api.getScence({
            method: 'GET',
          },
          key,
        )
        if (sence.code === 1000) {
          let value = JSON.parse(sence.data.value)
          let identifier = value.identifier;
          return identifier
        }
      },
      changeTaskStatus() {
        this.doTask = 0
        getApp().finishTask(this.taskCenterCode, this.taskContentId, this.taskContentName, 0)
      },
      async taskStatus() {
        let info = await getApp().getTaskInfo()
        if (!info.contentList) {
          this.doTask = 3
          return false
        }
        let list = info.contentList && info.contentList[0].content
        this.taskCenterCode = info.contentList[0].taskCenterCode
        list && list.map(item => {
          if (item.taskContentType == 'Scan') {
            this.taskContentId = item.taskContentId
            this.taskContentName = item.taskContentName
            this.requiredTime = item.requiredTime || 10
            if (item.taskContentStatus > 3) {
              this.doTask = 0
            } else {
              this.doTask = 1
            }
          }
        })
      },

      //接收已满18周岁弹层子组件传值
      agePassStatus(val) {
        let that = this;
        that.isFullOld = val;
      },
      /**
       * CMS配置页面
       */
      getCMSPageInfo: async function(identifier, merchantId, storeId) {
        let that = this;
        let mt = '1.0';
        const json = await api.getConfigDetail({
          method: 'POST',
          query: {
            "identifier": identifier,
            "merchantId": merchantId,
            "storeId": storeId,
            "mt": mt
          }
        });
        if (json.data.code === 1000 && json.data.data !== null) {
          let configData = json.data.data;
          let cmsConfigData = {};
          if (this.preview) {
            cmsConfigData = JSON.parse(configData.preview);
          } else {
            cmsConfigData = JSON.parse(configData.content)
            let contents = configData.contents;
            for (let index in contents) {
              let startTime = contents[index].startTime;
              startTime = startTime.substring(0, 19);
              startTime = startTime.replace(/-/g, '/');
              let startTimeTimestamp = new Date(startTime).getTime();
              if (startTimeTimestamp <= new Date().getTime()) {
                cmsConfigData = JSON.parse(contents[index].content);
                break;
              }
            }
          }
          let CMSItembanner = cmsConfigData,
            CMSItembannerImage = cmsConfigData[0];
          that.shareImage = CMSItembannerImage[0].data.src;
        }
      },
      pageTitle(val) {
        if (val.showTitle == 1) {
          this.navbarData.navbarTitle = this.title ? this.title : val.title;
        } else {
          this.navbarData.navbarTitle = '';
        }
        if (!val.enableShare) {
          uni.hideShareMenu()
        }
        let trackEn = this.pathTrackEn ? '&en=' + this.pathTrackEn : '';
        let trackEp = this.pathTrackEp ? '&ep=' + this.pathTrackEp : '';
        getApp().cl_tracker.track('mini_program_view', {
          path: this.isCurrentPage + '?identifier=' + this.pathOption + trackEn + trackEp,
          pageName: val.title ? val.title : 'cms',
        })

      },
      /**
       * 用户授权 && 判断用户登录状态
       */
      onGotUserInfoToRegister: function() {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || '';
        let memberInfo = uni.getStorageSync('memberDetails') || getApp().globalData.memberDetails;
        if (!customerInfo) {
          that.$commonFunction.commonLoginNew().then(res => {
            if (res.code !== 1000) {
              uni.reLaunch({
                url: '/pages/home/home'
              })
              return
            }
          }).catch(err => {
            uni.reLaunch({
              url: '/pages/home/home'
            })
          })
        }
      },
    }
  };
</script>

<style>
  page {
    height: 100%;
  }

  .ios_mob {
    width: 100vw;
    height: 110vh;
  }

  .an_mob {
    width: 100vw;
    height: 92vh;
  }

  /* 首页 */
  .cmsPage {
    margin-bottom: 10rpx;
  }

  .imgsize_1 {
    width: 750rpx;
    height: 1330rpx;
  }

  .imgsize_1080_600 {
    width: 694rpx;
    height: 694rpx;
  }

  .imgsize_750-1000 {
    width: 694rpx;
    height: 900rpx;
  }

  .imgsize_3 {
    width: 694rpx;
    height: 900rpx;
  }

  .imgsize_4 {
    width: 694rpx;
    height: 1020rpx;
  }

  .imgsize_5 {
    width: 694rpx;
    height: 900rpx;
  }

  .takeover {
    background-color: #666666;
    padding: 244rpx 0;
    text-align: center;
  }

  .takeover .mob_center {
    padding: 0 80rpx;
    text-align: center;
    color: #fff;
  }

  .takeover h2 {
    display: block;
    font-size: 64rpx;
    line-height: 76rpx;
    padding: 40rpx 0;
  }

  .takeover p {
    padding-bottom: 40rpx;
    font-size: 36rpx;
    line-height: 44rpx;
    display: block;
  }

  .takeover .title-card-link {
    margin: 20rpx auto;
    background-color: #ffffff;
    border: 1px solid #ffffff;
    font-size: 26rpx;
    line-height: 42rpx;
    letter-spacing: 0.0825em;
    text-align: center;
    width: 400rpx;
    padding: 24rpx 18rpx 16rpx 18rpx;
  }

  .ipxTakeover {
    background-color: #666666;
    padding: 333rpx 0;
    text-align: center;
  }

  .imgText {
    padding: 0 28rpx;
    margin-bottom: 30rpx;
  }

  .imgText .center_text h2 {
    margin-top: 26rpx;
    display: block;
  }

  .imgText .center_text p {
    white-space: normal;
  }

  .imgText .center_text .navBox {
    margin-top: 26rpx;
  }

  .imgText .center_text .navBox navigator {
    display: inline-block;
    text-decoration: underline;
  }

  .line {
    border-bottom: 1px solid #e7e7e7;
    margin: 90rpx 28rpx 0;
  }

  .company-info {
    padding: 20rpx 0;
    color: #999;
    font-size: 20rpx;
    background-color: rgb(239, 239, 239);
    text-align: center;
  }

  image {
    display: block;
  }

  .cut-down {
    height: 74rpx;
    position: fixed;
    left: 0;
    right: 0;
    z-index: 2;
  }

  .big-gray {
    background-color: #f7f5f4;
    height: 100vh;
    /* min-height: 90vh; */
  }

  .bg-gray {
    background-color: #f7f5f4;
    /* min-height: 90vh; */
  }
</style>
